import {Plugin} from 'vite'
import fs from 'fs'
import path from 'path'

interface ComponentResolver {
  (name: string): {
    importName: string
    path: string
  } | null
}

interface Options {
  mode: string
  dir?: string
  libraryName?: string
  output?: string
  deep?: boolean
  prefix?: string
  resolvers?: ComponentResolver[]
}

export default function globalComponents(options?: Options): Plugin {
  const {
    dir = 'src/components',
    libraryName = 'components-library',
    output = 'src/global-components.d.ts',
    deep = true,
    prefix = '',
    resolvers = []
  } = options || {}

  return {
    name: 'vite-plugin-global-components',
    enforce: 'pre',
    buildStart() {
      if (!options?.mode.startsWith("prod")) return;

      const componentsDir = path.join(process.cwd(), dir)
      const outputFile = path.join(process.cwd(), output)

      if (!fs.existsSync(componentsDir)) {
        console.warn(`Components directory not found: ${componentsDir}`)
        return
      }

      // 递归查找组件文件
      const findComponents = (dir: string): Array<{
        name: string
        importPath: string
      }> => {
        const files = fs.readdirSync(dir)
        let results: Array<{ name: string; importPath: string }> = []

        files.forEach(file => {
          const fullPath = path.join(dir, file)
          const stat = fs.statSync(fullPath)

          if (stat.isDirectory() && deep) {
            results = results.concat(findComponents(fullPath))
          } else if (
              (file.endsWith('.vue') || file.endsWith('.tsx')) &&
              file.startsWith(prefix)
          ) {
            const componentName = path.basename(file).replace(/\.(vue|tsx)$/, '')
            const relativePath = path.relative(componentsDir, fullPath)
            const importPath = path.join(libraryName, path.dirname(relativePath), componentName)
                .replace(/\\/g, '/')  // 确保路径使用正斜杠

            results.push({
              name: componentName,
              importPath: importPath
            })
          }
        })

        return results
      }

      // 获取自动发现的组件
      const autoComponents = findComponents(componentsDir)

      // 应用自定义解析器
      const resolvedComponents = resolvers.flatMap(resolver => {
        return autoComponents
            .map(comp => {
              const resolved = resolver(comp.name)
              if (!resolved) return null
              return {
                name: comp.name,
                importPath: resolved.path,
                importName: resolved.importName || comp.name
              }
            })
            .filter(Boolean) as Array<{ name: string; importPath: string; importName: string }>
      })

      // 组件合并
      const allComponents = [
        ...autoComponents.map(c => ({...c, importName: c.name})),
        ...resolvedComponents
      ]

      // 组件去重
      const comps = new Map(allComponents.map(c => [c.name, c]))
      const uniqueComponents = Array.from(comps).map(([_, c]) => c)

      if (uniqueComponents.length === 0) {
        console.warn(`No components found in ${componentsDir} matching prefix "${prefix}"`)
        return
      }

      // 生成类型声明内容
      const content = `
// Auto-generated by vite-plugin-global-components
declare module 'vue' {
  export interface GlobalComponents {
${uniqueComponents.map(c =>
          `    ${c.name}: typeof import('${libraryName}')['${c.importName}']`
      ).join('\n')}
  }
}

export {}
`
      // 确保输出目录存在
      fs.mkdirSync(path.dirname(outputFile), {recursive: true})

      // 写入输出文件
      fs.writeFileSync(outputFile, content)

      console.log(`Generated ${outputFile} with ${uniqueComponents.length} components`)
    }
  }
}